import React from 'react';
import { Layout, Spin, Empty, Button } from 'antd';
import { SettingOutlined, CloseOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useExperimentData } from '../hooks/useExperimentData';
import { useSeriesData } from '../hooks/useSeriesData';
import { useToolbar } from '../hooks/useToolbar';
import { useVisualization } from '../contexts/VisualizationContext';
import ExperimentList from '../components/experiments/ExperimentList';
import ExperimentInfoCard from '../components/experiments/ExperimentInfoCard';
import ResultFilesList from '../components/experiments/ResultFilesList';
import QuickNavigation from '../components/experiments/QuickNavigation';
import CategorySection from '../components/experiments/CategorySection';
import ExperimentToolbar from '../components/experiments/ExperimentToolbar';
import ExperimentTimeline from '../components/system/ExperimentTimeline';
import { NavigationProvider } from '../contexts/NavigationContext';
import '../config/chartConfig'; // 导入以注册 Chart.js 组件

const { Content } = Layout;

const ExperimentResults: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>();
  const navigate = useNavigate();

  // 使用自定义 Hooks 管理数据
  const {
    project,
    experiments,
    selectedExperiment,
    loading,
    detailLoading,
    setSelectedExperiment,
    handleSelectExperiment,
    refreshExperiments,
    removeExperimentFromList,
    updateExperimentBasicInfo,
  } = useExperimentData(projectId);

  const {
    seriesDataMap,
    clearSeriesData,
    loadSeriesData,
    getSeriesViewMode,
    updateSeriesViewMode,
  } = useSeriesData(projectId, selectedExperiment?.id || null);

  const {
    toolbarVisible,
    toolbarWidth,
    activeTool,
    isResizing,
    toolbarRef,
    resizeRef,
    handleToggleToolbar,
    handleCloseToolbar,
    handleToolSelect,
    setIsResizing,
  } = useToolbar();

  const { visualizationItems } = useVisualization();
  const prevVisualizationItemsCount = React.useRef(visualizationItems.length);

  // 当有新的可视化项目添加时，自动打开工具栏并切换到可视化标签
  React.useEffect(() => {
    if (visualizationItems.length > prevVisualizationItemsCount.current) {
      // 有新的项目添加
      if (!toolbarVisible) {
        handleToggleToolbar();
      }
      if (activeTool !== 'visualization') {
        handleToolSelect('visualization');
      }
    }
    prevVisualizationItemsCount.current = visualizationItems.length;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visualizationItems.length]);

  // 管理折叠状态
  const [collapsedKeys, setCollapsedKeys] = React.useState<string[]>([]);
  
  // 管理序列数据的展开状态
  const [expandedSeriesKeys, setExpandedSeriesKeys] = React.useState<(string | number)[]>([]);
  
  // 管理左侧边栏收起状态
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);

  // 当选中实验改变时，清空序列数据和折叠状态
  React.useEffect(() => {
    if (selectedExperiment) {
      clearSeriesData();
      setCollapsedKeys([]); // 默认全部折叠
      setExpandedSeriesKeys([]); // 默认全部折叠
    }
  }, [selectedExperiment?.id]);

  // 处理导航跳转并展开
  const handleNavigate = (key: string) => {
    setCollapsedKeys((prev) => {
      if (!prev.includes(key)) {
        return [...prev, key];
      }
      return prev;
    });
  };

  // 结果文件折叠变化（仅影响 'result-files'）
  const handleResultFilesCollapseChange = (key: string | string[]) => {
    const isActive = Array.isArray(key) ? key.includes('result-files') : key === 'result-files';
    setCollapsedKeys(prev => {
      const without = prev.filter(k => k !== 'result-files');
      return isActive ? [...without, 'result-files'] : without;
    });
  };

  // 分类折叠变化（仅影响对应分类，不影响其他已展开项）
  const handleCategoryCollapseChangeFor = React.useCallback((categoryId: number, key: string | string[]) => {
    const categoryKey = `category-${categoryId}`;
    const isActive = Array.isArray(key) ? key.includes(categoryKey) : key === categoryKey;
    setCollapsedKeys(prev => {
      const without = prev.filter(k => k !== categoryKey);
      return isActive ? [...without, categoryKey] : without;
    });
  }, []);

  // 计算所有可能的 keys
  const getAllKeys = React.useMemo(() => {
    const keys: string[] = [];
    if (selectedExperiment?.results && selectedExperiment.results.length > 0) {
      keys.push('result-files');
    }
    if (selectedExperiment?.categories) {
      selectedExperiment.categories.forEach(category => {
        keys.push(`category-${category.id}`);
      });
    }
    return keys;
  }, [selectedExperiment]);

  // 一键展开所有
  const handleExpandAll = () => {
    setCollapsedKeys(getAllKeys);
  };

  // 一键收起所有
  const handleCollapseAll = () => {
    setCollapsedKeys([]);
  };

  // 检查是否有展开的项
  const hasExpanded = collapsedKeys.length > 0;

  // 处理序列数据展开
  const handleSeriesExpand = (keys: (string | number)[]) => {
    setExpandedSeriesKeys(keys);
    keys.forEach((key) => {
      const seriesId = parseInt(key as string);
      if (!seriesDataMap[seriesId]?.data) {
        loadSeriesData(seriesId);
      }
    });
  };

  // 展开分类和序列数据
  const expandCategoryAndSeries = React.useCallback((
    categoryId: number,
    seriesId: number
  ) => {
    const categoryKey = `category-${categoryId}`;
    
    // 展开分类
    setCollapsedKeys((prev) => {
      if (!prev.includes(categoryKey)) {
        return [...prev, categoryKey];
      }
      return prev;
    });

    // 展开序列数据并加载数据
    setTimeout(() => {
      // 先设置展开状态
      setExpandedSeriesKeys([String(seriesId)]);
      // 然后加载数据
      handleSeriesExpand([seriesId]);
      
      // 滚动到序列数据位置
      setTimeout(() => {
        // 尝试滚动到序列数据的容器
        const seriesElement = document.querySelector(`[data-series-id="${seriesId}"]`);
        if (seriesElement) {
          seriesElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
          // 高亮显示
          (seriesElement as HTMLElement).style.backgroundColor = '#e6f7ff';
          setTimeout(() => {
            (seriesElement as HTMLElement).style.backgroundColor = '';
          }, 2000);
        } else {
          // 如果找不到序列元素，至少滚动到分类
          const categoryElement = document.getElementById(`category-${categoryId}`);
          if (categoryElement) {
            categoryElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
          }
        }
      }, 300);
    }, 200);
  }, [handleSeriesExpand]);

  // 存储待跳转的目标信息
  const pendingNavigationRef = React.useRef<{
    experimentId: number;
    categoryId: number;
    seriesId: number;
  } | null>(null);

  // 处理从可视化面板跳转到序列数据
  const handleNavigateToSeries = React.useCallback((
    experimentId: number,
    categoryId: number,
    seriesId: number
  ) => {
    // 1. 如果当前选择的实验不是目标实验，先切换到目标实验
    if (selectedExperiment?.id !== experimentId) {
      const targetExperiment = experiments.find(exp => exp.id === experimentId);
      if (targetExperiment) {
        // 保存待跳转的目标信息
        pendingNavigationRef.current = { experimentId, categoryId, seriesId };
        // 切换到目标实验
        handleSelectExperiment(targetExperiment);
        return;
      }
    }
    
    // 2. 如果已经是目标实验，直接展开
    expandCategoryAndSeries(categoryId, seriesId);
  }, [selectedExperiment, experiments, handleSelectExperiment, expandCategoryAndSeries]);

  // 监听实验加载完成，执行待处理的跳转
  React.useEffect(() => {
    // 只有在实验加载完成且有待处理的跳转时才执行
    if (
      !detailLoading &&
      pendingNavigationRef.current &&
      selectedExperiment?.id === pendingNavigationRef.current.experimentId
    ) {
      const { categoryId, seriesId } = pendingNavigationRef.current;
      // 清除待处理标记
      pendingNavigationRef.current = null;
      // 执行展开
      expandCategoryAndSeries(categoryId, seriesId);
    }
  }, [detailLoading, selectedExperiment?.id, expandCategoryAndSeries]);

  // 处理工具栏拖拽
  const handleResizeStart = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsResizing(true);
  };

  const handleResizeEnter = (e: React.MouseEvent) => {
    if (!isResizing) {
      (e.currentTarget.firstElementChild as HTMLElement).style.background = '#1890ff';
    }
  };

  const handleResizeLeave = (e: React.MouseEvent) => {
    if (!isResizing) {
      (e.currentTarget.firstElementChild as HTMLElement).style.background = '#d9d9d9';
    }
  };

  if (loading) {
    return (
      <Layout style={{ minHeight: '100vh' }}>
        <Content style={{ padding: '50px', textAlign: 'center' }}>
          <Spin size="large" />
        </Content>
      </Layout>
    );
  }

  if (!project) {
    return (
      <Layout style={{ minHeight: '100vh' }}>
        <Content style={{ padding: '50px' }}>
          <Empty description="项目不存在" />
        </Content>
      </Layout>
    );
  }

  return (
    <Layout style={{ minHeight: '100vh', height: '100vh', overflow: 'hidden' }}>
      {/* 左侧实验列表 */}
      <ExperimentList
        experiments={experiments}
        selectedExperiment={selectedExperiment}
        onSelectExperiment={handleSelectExperiment}
        onClearSelection={() => setSelectedExperiment(null)}
        collapsed={sidebarCollapsed}
        onCollapseChange={setSidebarCollapsed}
        onRefresh={refreshExperiments}
        onRemoveExperiment={removeExperimentFromList}
        projectNameEn={projectId}
      />

      {/* 右侧实验详情 */}
      <Content
        style={{
          background: '#f0f2f5',
          padding: '24px',
          marginLeft: sidebarCollapsed ? '64px' : '300px',
          marginRight: toolbarVisible ? `${toolbarWidth}px` : '0',
          height: '100vh',
          overflow: 'auto',
          transition: 'margin-left 0.2s, margin-right 0.3s ease'
        }}
      >
        {/* 工具栏按钮 - 右下角，始终显示 */}
        <div
          style={{
            position: 'fixed',
            bottom: '24px',
            right: toolbarVisible ? `${toolbarWidth + 24}px` : '24px', // 工具栏打开时，按钮移到工具栏左侧
            zIndex: 1001,
            transition: 'right 0.2s ease',
          }}
        >
          <Button
            type="primary"
            icon={toolbarVisible ? <CloseOutlined /> : <SettingOutlined />}
            shape="circle"
            size="large"
            onClick={handleToggleToolbar}
            style={{
              boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
              width: '48px',
              height: '48px'
            }}
          />
        </div>

        <div style={{ maxWidth: '1200px', margin: '0 auto', width: '100%' }}>
          {!selectedExperiment ? (
            <ExperimentTimeline
              onExperimentClick={async (experiment) => {
                // 如果当前项目不匹配，需要先切换项目
                if (projectId !== experiment.projectNameEn) {
                  navigate(`/project/${experiment.projectNameEn}/experiments`);
                  return;
                }
                
                // 在同一个项目内，找到对应的实验并选择
                const targetExperiment = experiments.find(exp => exp.id === experiment.id);
                if (targetExperiment) {
                  await handleSelectExperiment(targetExperiment);
                }
              }}
            />
          ) : detailLoading ? (
            <div style={{ textAlign: 'center', padding: '100px 0' }}>
              <Spin size="large" />
            </div>
          ) : (
            <div>
              {/* 快速导航 */}
              {(selectedExperiment.results && selectedExperiment.results.length > 0) ||
              (selectedExperiment.categories && selectedExperiment.categories.length > 0) ? (
                <QuickNavigation 
                  categories={selectedExperiment.categories || []} 
                  hasResults={!!(selectedExperiment.results && selectedExperiment.results.length > 0)}
                  onNavigate={handleNavigate}
                  hasExpanded={hasExpanded}
                  onExpandAll={handleExpandAll}
                  onCollapseAll={handleCollapseAll}
                />
              ) : null}

              {/* 实验基本信息 */}
              <ExperimentInfoCard 
                experiment={selectedExperiment}
                projectNameEn={projectId || ''}
                onUpdateExperiment={updateExperimentBasicInfo}
                onViewParameters={() => {
                  if (!toolbarVisible) {
                    handleToggleToolbar();
                  }
                  handleToolSelect('parameters');
                }}
              />

              {/* 结果文件 */}
              {selectedExperiment.results && selectedExperiment.results.length > 0 && (
                <ResultFilesList 
                  results={selectedExperiment.results}
                  activeKey={collapsedKeys.includes('result-files') ? 'result-files' : undefined}
                  onChange={handleResultFilesCollapseChange}
                />
              )}

              {/* 数据分类 */}
              {selectedExperiment.categories && selectedExperiment.categories.length > 0 && (
                <div>
                  {selectedExperiment.categories.map((category) => (
                    <CategorySection
                      key={category.id}
                      category={category}
                      experimentId={selectedExperiment.id}
                      experimentName={selectedExperiment.name}
                      seriesDataMap={seriesDataMap}
                      getSeriesViewMode={getSeriesViewMode}
                      updateSeriesViewMode={updateSeriesViewMode}
                      onLoadSeriesData={loadSeriesData}
                      onSeriesExpand={handleSeriesExpand}
                      activeKey={collapsedKeys}
                      onChange={(k) => handleCategoryCollapseChangeFor(category.id, k)}
                      expandedSeriesKeys={expandedSeriesKeys}
                    />
                  ))}
                </div>
              )}

              {(!selectedExperiment.results || selectedExperiment.results.length === 0) &&
                (!selectedExperiment.categories || selectedExperiment.categories.length === 0) && (
                  <Empty description="该实验暂无结果数据" />
                )}
            </div>
          )}
        </div>
      </Content>

      {/* 右侧工具栏面板 */}
      <NavigationProvider navigateToSeries={handleNavigateToSeries}>
        <ExperimentToolbar
          visible={toolbarVisible}
          width={toolbarWidth}
          activeTool={activeTool}
          isResizing={isResizing}
          toolbarRef={toolbarRef}
          resizeRef={resizeRef}
          onToolSelect={handleToolSelect}
          onClose={handleCloseToolbar}
          onResizeStart={handleResizeStart}
          onResizeEnter={handleResizeEnter}
          onResizeLeave={handleResizeLeave}
          projectNameEn={projectId}
          experiment={selectedExperiment}
        />
      </NavigationProvider>
    </Layout>
  );
};

export default ExperimentResults;
